import { useCallback, useRef, useEffect } from 'react';
import { setGlobalRef } from '@/utils/utils';

/**
 * 可用于获取grid相关api，以及清空选中项的操作
 * @param props
 */
export function useGrid(props) {
  const { loading, setRowKeysFunc, setRowsFunc, onReadyCallback } = props;

  const gridApiRef = useRef({});
  const gridManagerRef = useRef({});
  const gridColumnApiRef = useRef({});

  const onGridReady = useCallback(
    (api, gridManager) => {
      setGlobalRef({
        title: '列表',
        key: gridManager.gridKey,
        schema: gridManager.columnsDefs,
        type: 'grid',
        ref: api.api,
      });
      gridApiRef.current = api.api;
      gridManagerRef.current = gridManager;
      gridColumnApiRef.current = api.columnApi;
      onReadyCallback &&
        onReadyCallback({
          gridApi: api.api,
          gridManager: gridManager,
          gridColumnApi: api.columnApi,
        });
    },
    [onReadyCallback],
  );

  useEffect(() => {
    if (loading) {
      // gridApiRef.current?.deselectAll?.()
      setRowKeysFunc && setRowKeysFunc([]);
      setRowsFunc && setRowsFunc([]);
    }
  }, [loading]);

  return {
    onGridReady,
    gridApiRef,
    gridManagerRef,
    gridColumnApiRef,
  };
}
